# -*- coding: UTF-8 -*-
# 2023/12/3 18:39
import tkinter as tk
from tkinter import ttk

import ttkbootstrap as ttkb


class int_placeholder_Entry(ttk.Entry):
    def __init__(self, master=None, placeholder="灰色提示文字", placeholder_color='grey', width=6, **kwargs):
        """
        在实例化时填写validate和validatecommand参数即可,self.register_validatecommand参数可能需要先实例化后获得
        validate='key', validatecommand=(, '%d', '%S')
        """
        super().__init__(master, width=width, **kwargs)

        self.placeholder = placeholder
        self.placeholder_color = placeholder_color
        self.default_fg_color = self.cget('foreground')
        self.showing_placeholder = True

        self.bind("<FocusIn>", self.foc_in)
        self.bind("<FocusOut>", self.foc_out)

        self.register_validatecommand = self.register(self.is_positive_integer)

        # 如果有默认参数输入就忽略占位符
        try:
            textvariable = kwargs["textvariable"]
        except KeyError:
            self.put_placeholder()

    def put_placeholder(self):
        if self.get() == "" or self.get() != self.placeholder:
            self.insert(0, self.placeholder)
            self['foreground'] = self.placeholder_color
            self.showing_placeholder = True

    def foc_in(self, event=None):
        if self.showing_placeholder and not self.get:
            self.delete(0, tk.END)
            self['foreground'] = self.default_fg_color
            self.showing_placeholder = False

    def foc_out(self, event=None):
        if self.get() == "":
            self.put_placeholder()

    def is_positive_integer(self, action, content):
        """
        验证正整数
        """
        if action == '1':  # 插入操作
            if content != self.placeholder:
                if not content.isdigit() or int(content) <= 0:
                    return False

        return True


if __name__ == '__main__':
    # 创建主窗口
    root = ttkb.Window(themename='litera')
    root.minsize(200, 200)

    # 创建带有灰色提示文字的Entry控件
    entry_with_placeholder = int_placeholder_Entry(root, placeholder="请输入文字", )
    entry_with_placeholder.pack(pady=10, padx=10)
    entry_with_placeholder.config(validate='key', validatecommand=(entry_with_placeholder.register_validatecommand, '%d', '%S'))

    entry_with_placeholder1 = int_placeholder_Entry(root)
    entry_with_placeholder1.pack(pady=10, padx=10)
    entry_with_placeholder1.config(validate='key', validatecommand=(entry_with_placeholder1.register_validatecommand, '%d', '%S'))

    # 启动事件循环
    root.mainloop()
